package com.gxgeek.interview.t2;

import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by gx on 2017/5/4.
 */
public class Sensitive {
    private static final Logger logger = LoggerFactory.getLogger(Sensitive.class);

    private static final String DEFAULT_REPLACEMENT = "*";


    private class TrieNode {
        //关键词结尾
        private boolean end = false;

        //当前结尾下所有子节点
        private Map<Character, TrieNode> subNodes = new HashMap<>();

        public void addSubNodes(Character key, TrieNode trieNode) {
            subNodes.put(key, trieNode);
        }

        TrieNode getSubNode(Character key) {
            return subNodes.get(key);
        }


        boolean isKeyWordEnd() {
            return end;
        }

        void setKeyWordEnd(boolean end) {
            this.end = end;
        }


    }

    private TrieNode rootNode = new TrieNode();

    //添加关键字
    public void addWord(String lineTxt) {
        TrieNode trieNode = rootNode;//获取当前节点
        for (int i = 0; i < lineTxt.length(); ++i) {   //遍历当前节点
            Character c = lineTxt.charAt(i); //当前字符

            TrieNode node = trieNode.getSubNode(c); //当前节点子节点

            if (node == null) {
                node = new TrieNode();
                trieNode.addSubNodes(c, node);
            }

            trieNode = node ; // 指向下一个节点
            if (i == lineTxt.length() - 1) { //如果是最后一个节点
                //标记最后一个节点
                node.setKeyWordEnd(true);
            }
        }
    }

    public String filter(String text) {
        //如果文字为空直接返回
        if (StringUtils.isBlank(text)) {
            return text;
        }
        //返回结果初始化
        StringBuilder result = new StringBuilder();


        TrieNode tempNode = rootNode;

        int begin = 0; // 回滚数
        int position = 0; // 当前比较的位置

        while (position < text.length()) {
            char c = text.charAt(position);//取出当前值
            // 空格直接跳过
            if (isSymbol(c)) {
                if (tempNode == rootNode) {
                    result.append(c);
                    ++begin;
                }
                ++position;
                continue;
            }

            if (position!=0&& c == text.charAt(position-1) ){ //如果和上一个字相同
                ++position;

                continue;
            }

            tempNode = tempNode.getSubNode(c);

            // 当前位置的匹配结束
            if (tempNode == null) {//找不到 全部返回
                // 以begin开始的字符串不存在敏感词
                result.append(text.charAt(begin));
                // 跳到下一个字符开始测试
                position = begin + 1;
                begin = position;
                // 回到树初始节点
                tempNode = rootNode;
            } else if (tempNode.isKeyWordEnd()) {  //如果是最后一个位置
                // 发现敏感词， 从begin到position的位置用replacement替换掉
                result.append(DEFAULT_REPLACEMENT);
                position = position + 1;  // 向前一个位置 监测
                begin = position;
                tempNode = rootNode;  //重新指向根节点
            } else {
                ++position;   //不是最后一个位置   向前一个位置继续检测
            }
        }

        result.append(text.substring(begin));

        return result.toString();
    }

    /**
     * 判断是否是一个符号
     * @param c
     * @return
     */
    private boolean isSymbol(char c) {
        int ic = (int) c;
        // 0x2E80-0x9FFF 东亚文字范围
        return !CharUtils.isAsciiAlphanumeric(c) && (ic < 0x2E80 || ic > 0x9FFF);
    }

    //初始化读取配置文件
    public void init(){
        this.rootNode = new TrieNode();
        try {
            InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("SensitiveWords.txt");
            InputStreamReader read = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                lineTxt = lineTxt.trim();
                addWord(lineTxt);
            }
            read.close();
        } catch (Exception e) {
            logger.error("读取敏感词文件失败" + e.getMessage());
        }

    }

    public static void main(String[] argv) {
        Sensitive s = new Sensitive();
        s.addWord("色情");
        s.addWord("好色");
        System.out.print(s.filter("你好X色色情情情情XX"));
        System.out.println();;
    }

}
